import { forwardRef, useEffect } from 'react';
import { CloseCircleOutlined } from '@ant-design/icons';
import { Form } from '@formily/core';
import { getMessage, TextWidget } from '@inbiz/react';
import { Button, Empty, Input, Select } from 'antd';
import { useQueryFields } from '@inbiz/hooks';
import { uuid } from '@inbiz/utils';
import type { SourceDataType, FormValueType } from './ConfigModal';
import './configModal.less';

type ISourceFormProps = {
  globalForm: Form<any> & {
    appInfo?:
    | {
      appId: string;
    }
    | undefined;
  };
  sourceData: SourceDataType[];
  setSourceData: (data: any) => void;
  formValue: FormValueType;
  setFormValue: (data: any) => void;
};

const { Option } = Select;

const SourceForm = forwardRef((props: ISourceFormProps, ref) => {
  const { globalForm, formValue, sourceData, setFormValue, setSourceData } = props;
  //@ts-ignore
  const [fields] = useQueryFields({
    //@ts-ignore
    key: globalForm.fields?.['form.senior.soure.x-component-props.sourceModel']?.value,
    appId: globalForm?.appInfo?.appId,
  });

  const recordNumChange = (e: any) => {
    setFormValue((formValue: any) => {
      let oldFormValue = { ...formValue };
      oldFormValue.recordNum = e.target?.value;
      return oldFormValue;
    });
  };

  const timeChange = (v: string) => {
    setFormValue((formValue: any) => {
      let oldFormValue = { ...formValue };
      oldFormValue.timeKey = v;
      oldFormValue.timeStatus = false;
      return oldFormValue;
    });
  };

  const contentChange = (v: string, index: number) => {
    setSourceData((source: any) => {
      let oldSource = [...source];
      oldSource[index].value = v;
      oldSource[index].status = false;
      return oldSource;
    });
  };

  const add = () => {
    setSourceData((source: any) => {
      let oldSource = [...source];
      let statusValue = oldSource
        .map((item, index) => {
          if (!item.value) {
            return index;
          }
          return;
        })
        .filter((v) => v !== undefined);
      if (statusValue.length === 0) {
        oldSource.push({
          key: uuid(0, 16),
          value: undefined,
          splitJoint: undefined,
          status: false,
        });
      } else {
        statusValue.forEach((item) => {
          oldSource[item!].status = true;
        });
      }

      return oldSource;
    });
  };

  const splitJointChange = (e: any, index: number) => {
    setSourceData((source: any) => {
      let oldSource = [...source];
      oldSource[index].splitJoint = e.target.value;
      return oldSource;
    });
  };

  const remove = (index: number) => {
    setSourceData((source: any) => {
      let oldSource = [...source];
      oldSource[index - 1].splitJoint = undefined;
      oldSource.splice(index, 1);
      return oldSource;
    });
  };

  useEffect(() => {
    if (!formValue.timeKey) {
      setFormValue((formValue: any) => {
        let oldFormValue = { ...formValue };
        oldFormValue.recordNum = 10;
        return oldFormValue;
      });
    }
  }, []);
  return (
    <div className="sourceForm">
      <div className="sourceFormItem">
        <div className="sourceFormItemBox">
          <div className="sourceFormItemXin">*</div>
          <div className="sourceFormItemTitle">
            <TextWidget>TimeLine.time</TextWidget>：
          </div>
        </div>
        <Select
        showSearch
        filterOption={(input, option) =>
          (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
        }
          placeholder={getMessage('TimeLine.pleaseSelect')}
          allowClear
          value={formValue.timeKey || null}
          onChange={(v) => {
            timeChange(v);
          }}
          notFoundContent={
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={<TextWidget>pageselect.no_data</TextWidget>}
            />
          }
          status={formValue.timeStatus ? 'error' : ''}
        >
          {fields.map((option) => (
            <Option
              key={uuid(0, 16)}
              value={`${option.origin_FieldName?.split('$')?.[1]
                ? option.origin_FieldName?.split('$')?.[1]
                : ''
                }$${option.value}`}
            >
              {option.value}
            </Option>
          ))}
        </Select>
        {formValue.timeStatus ? (
          <div className="status">
            <TextWidget>TimeLine.pleaseSelectData</TextWidget>！
          </div>
        ) : null}
      </div>
      {sourceData?.map((item, index) => {
        if (index === 0) {
          return (
            <div className="sourceFormItem">
              <div className="sourceFormItemBox">
                <div className="sourceFormItemXin">*</div>
                <div className="sourceFormItemTitle">
                  <TextWidget>TimeLine.nodeContent</TextWidget>：
                </div>
              </div>
              <Select
              showSearch
              filterOption={(input, option) =>
               (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
             }
                placeholder={getMessage('TimeLine.pleaseSelect')}
                allowClear
                value={item.value}
                onChange={(v) => {
                  contentChange(v, index);
                }}
                status={item.status ? 'error' : ''}
              >
                {fields.map((option) => (
                  <Option
                    key={uuid(0, 16)}
                    value={`${option.origin_FieldName?.split('$')?.[1]
                      ? option.origin_FieldName?.split('$')?.[1]
                      : ''
                      }$${option.value}`}
                  >
                    {option.value}
                  </Option>
                ))}
              </Select>
              {item.status ? (
                <div className="status">
                  <TextWidget>TimeLine.pleaseSelectData</TextWidget>！
                </div>
              ) : null}
              {index < sourceData.length - 1 ? (
                <Input
                  placeholder={getMessage('TimeLine.enterJoinSymbole')}
                  className="splitJoint"
                  value={item.splitJoint}
                  onChange={(e) => {
                    splitJointChange(e, index);
                  }}
                />
              ) : null}
            </div>
          );
        } else {
          return (
            <div className="sourceFormItem">
              <div className="sourceFormItemBox">
                <div className="sourceFormItemXin"></div>
                <div className="sourceFormItemTitle"></div>
              </div>
              <Select
                placeholder={getMessage('TimeLine.pleaseSelect')}
                allowClear
                value={item.value}
                onChange={(v) => {
                  contentChange(v, index);
                }}
                status={item.status ? 'error' : ''}
                showSearch
                filterOption={(input, option) =>
                 (option?.value ?.toString()?? '').toLowerCase().includes(input.toLowerCase())
               }
              >
                {fields.map((option) => (
                  <Option
                    key={uuid(0, 16)}
                    value={`${option.origin_FieldName?.split('$')?.[1]
                      ? option.origin_FieldName?.split('$')?.[1]
                      : ''
                      }$${option.value}`}
                  >
                    {option.value}
                  </Option>
                ))}
              </Select>
              {item.status ? (
                <div className="status">
                  <TextWidget>TimeLine.pleaseSelectData</TextWidget>！
                </div>
              ) : null}
              {index < sourceData.length - 1 ? (
                <Input
                  placeholder={getMessage('TimeLine.enterJoinSymbole')}
                  className="splitJoint"
                  value={item.splitJoint}
                  onChange={(e) => {
                    splitJointChange(e, index);
                  }}
                />
              ) : null}
              {index === sourceData.length - 1 ? (
                <CloseCircleOutlined
                  className="removeIcon"
                  onClick={() => {
                    remove(index);
                  }}
                />
              ) : null}
            </div>
          );
        }
      })}
      <div className="sourceFormItem">
        <div className="sourceFormItemBox"></div>
        <Button onClick={() => add()}>
          +<TextWidget>TimeLine.btn.add</TextWidget>
        </Button>
      </div>
      <div className="sourceFormItem">
        <div className="sourceFormItemBox">
          <div className="sourceFormItemTitle">
            <TextWidget>TimeLine.recordsNumber</TextWidget>：
          </div>
        </div>
        <Input
          value={formValue.recordNum}
          onChange={(e) => {
            recordNumChange(e);
          }}
          className="recordNumInput"
        />
      </div>
    </div>
  );
});

export default SourceForm;
